package com.example.studyllm.component.ai.model.service;

import com.example.studyllm.bo.ChatBO;
import com.example.studyllm.bo.ModelBO;
import com.example.studyllm.bo.CompletionRes;
import com.example.studyllm.bo.StreamEmitter;
import com.example.studyllm.config.exception.BusinessException;
import com.example.studyllm.entity.rag.RagModel;
import com.example.studyllm.service.rag.RagModelService;
import com.example.studyllm.utils.POJOConverter;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;


@Service
public class ChatUtils {

    @Resource
    private ModelFactory langChatService;

    @Resource
    private RagModelService ragModelService;

    public SseEmitter handler(StreamEmitter emitter, ChatBO req) {

        RagModel model = ragModelService.getById(req.getModelId());
        ModelBO modelBO = new ModelBO();
        POJOConverter.copy(model,modelBO);
        if(model==null){
            throw new BusinessException("无对应的模型配置");
        }

        langChatService
                .chatStream(modelBO,req)
                .onPartialResponse(token -> {
                    CompletionRes res = CompletionRes.process(token);
                    emitter.send(res);
                }).onCompleteResponse(c -> {
                    CompletionRes res = CompletionRes.end(c);
                    emitter.send(res);
                    emitter.complete();
                }).onError(e -> {
                    emitter.error(e.getMessage());
                }).start();

        return emitter.get();
    }
}
